'use strict'

const router = require('koa-router')()
const fs = require('fs')

function getFilePath(filePath){
    let files = fs.readdirSync(filePath)
    let routeFile = files.filter(item=>{
        return item.endsWith('.js') && item!='index.js'
    })
    return routeFile
}

function createRoute(routeFile){
    routeFile.forEach(item=>{
        let tmpPath = __dirname+'/'+item
        let obj = require(tmpPath)
        for(let i in obj){
            let tmpArr = i.split(' ')
            let rMethod = tmpArr[0]
            let rPath = tmpArr[1]
            let rFunction = obj[i]
            if(rMethod == 'get'){
                router.get(rPath,rFunction)
            }else if (rMethod == 'post'){
                router.post(rPath,rFunction)
            }else if (rMethod == 'put'){
                router.put(rPath,rFunction)
            }else if (rMethod == 'delete'){
                router.delete(rPath,rFunction)
            }
        }
    })
}

let routeFiles = getFilePath(__dirname)
createRoute(routeFiles)

module.exports = router